<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">楼宇管理</h1>
      <div class="header-controls">
        <!-- 小区选择下拉框 -->
        <div class="community-selector">
          <el-select
            v-model="selectedCommunityId"
            placeholder="请选择小区"
            clearable
            style="width: 300px"
            @change="handleCommunityChange"
          >
            <el-option
              v-for="community in communityList"
              :key="community.id"
              :label="community.name"
              :value="community.id"
            />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 楼宇内容区域 -->
    <div class="content-area">
      <div v-if="!selectedCommunityId" class="empty-state">
        <IconifyIconOffline icon="ep:office-building" class="empty-icon" />
        <p class="empty-text">请先选择小区</p>
      </div>
      <div v-else class="building-content">
        <div class="community-info">
          <p class="community-name">已选择小区: {{ selectedCommunityName }}</p>
          <p class="community-address">
            小区地址: {{ selectedCommunityAddress }}
          </p>
        </div>

        <!-- 楼栋管理区域 -->
        <div class="building-management">
          <!-- 左侧楼栋类型标签页 -->
          <div class="building-types">
            <el-tabs v-model="activeType" @tab-change="handleTypeChange">
              <el-tab-pane
                v-for="type in buildingTypes"
                :key="type.id"
                :label="type.name"
                :name="type.name"
              >
                <div class="building-list">
                  <div v-if="buildingList.length === 0" class="empty-buildings">
                    <IconifyIconOffline
                      icon="ep:office-building"
                      class="empty-icon"
                    />
                    <p>该类型暂无楼栋</p>
                    <el-button
                      type="primary"
                      size="small"
                      class="add-building-btn"
                      @click="openCreateDialog"
                    >
                      <IconifyIconOffline icon="ep:plus" />
                      添加楼栋
                    </el-button>
                  </div>
                  <div v-else class="building-nav">
                    <!-- 楼栋列表头部 -->
                    <div class="building-nav-header">
                      <h3 class="nav-title">楼栋</h3>
                      <el-button
                        type="primary"
                        size="small"
                        @click="openCreateDialog"
                      >
                        <IconifyIconOffline icon="ep:plus" />
                        +增加楼栋
                      </el-button>
                    </div>

                    <!-- 楼栋列表 -->
                    <ul class="building-nav-list">
                      <li
                        v-for="building in buildingList"
                        :key="building.id"
                        class="building-nav-item"
                        :class="{ active: selectedBuildingId === building.id }"
                        @click="selectBuilding(building)"
                      >
                        <span class="building-name">{{ building.name }}</span>
                        <div class="building-actions">
                          <el-button
                            type="warning"
                            size="small"
                            @click="handleBuildingEdit(building)"
                          >
                            修改楼栋
                          </el-button>
                          <el-button
                            type="danger"
                            size="small"
                            @click="handleBuildingDelete(building)"
                          >
                            删除楼栋
                          </el-button>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 右侧楼栋房屋详细信息 -->
          <div class="building-details">
            <div v-if="!selectedBuilding" class="empty-details">
              <IconifyIconOffline
                icon="ep:office-building"
                class="empty-icon"
              />
              <p>请选择楼栋查看详细信息</p>
              <p class="debug-info">
                当前楼栋列表数量: {{ buildingList.length }}
              </p>
              <p class="debug-info">当前选中楼栋ID: {{ selectedBuildingId }}</p>
            </div>
            <div v-else class="building-info-panel">
              <!-- 楼栋基本信息 -->
              <div class="building-info-header">
                <h2 class="building-title">{{ selectedBuilding.name }}</h2>
                <div class="building-basic-info">
                  <div class="info-row">
                    <div class="info-item">
                      <span class="label">楼宇朝向:</span>
                      <span class="value">{{
                        selectedBuilding.orientation || "未设置"
                      }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">楼高:</span>
                      <span class="value">
                        {{ selectedBuilding.heightM }}米
                      </span>
                    </div>
                    <div class="info-item">
                      <span class="label">楼宇结构:</span>
                      <span class="value">{{
                        selectedBuilding.structure || "未设置"
                      }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 楼层和房屋信息 -->
              <div class="floors-container">
                <div class="floors-header">
                  <h3>楼层房屋管理</h3>
                  <div class="floors-actions">
                    <el-button
                      type="primary"
                      size="small"
                      @click="openAddHouseDialog"
                    >
                      添加房屋
                    </el-button>
                    <el-button
                      type="info"
                      size="small"
                      :disabled="selectedHouses.length !== 1"
                      @click="openHouseDetailDialog"
                    >
                      查看详情
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      :disabled="selectedHouses.length === 0"
                      @click="deleteSelectedHouses"
                    >
                      删除
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="deleteAllHouses"
                    >
                      删除所有
                    </el-button>
                    <el-button
                      type="success"
                      size="small"
                      @click="openGenerateHousesDialog"
                    >
                      <IconifyIconOffline icon="ep:magic-stick" />
                      生成所有房屋
                    </el-button>
                  </div>
                </div>
                <div class="floors-content">
                  <div
                    v-if="unitList.length === 0 && floorList.length === 0"
                    class="empty-houses"
                  >
                    <p>暂无楼层和单元数据</p>
                    <p class="debug-info">单元数量: {{ unitList.length }}</p>
                    <p class="debug-info">楼层数量: {{ floorList.length }}</p>
                    <p class="debug-info">
                      当前楼栋ID: {{ selectedBuildingId }}
                    </p>
                  </div>
                  <div v-else class="house-grid">
                    <!-- 房屋网格表格 -->
                    <table class="house-table">
                      <thead>
                        <tr>
                          <th class="floor-header">楼层</th>
                          <th
                            v-for="unit in getUnits()"
                            :key="unit"
                            class="unit-header"
                          >
                            {{ unit }}
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="floor in getFloors()" :key="floor">
                          <td class="floor-cell">{{ floor }}</td>
                          <td
                            v-for="unit in getUnits()"
                            :key="`${floor}-${unit}`"
                            class="unit-cell"
                          >
                            <div class="houses-in-cell">
                              <div
                                v-for="house in getHousesByUnitAndFloor(
                                  unit,
                                  floor
                                )"
                                :key="house.room"
                                class="house-item"
                                :class="{
                                  selected:
                                    house.roomId &&
                                    selectedHouses.includes(house.roomId),
                                  'status-idle': house.status === 0,
                                  'status-occupied': house.status === 1,
                                  'status-rented': house.status === 2
                                }"
                                @click="
                                  house.roomId && handleHouseSelect(house.room)
                                "
                              >
                                <el-checkbox
                                  :model-value="
                                    house.roomId &&
                                    selectedHouses.includes(house.roomId)
                                  "
                                  :disabled="!house.roomId"
                                  class="house-checkbox"
                                  @change="handleHouseSelect(house.room)"
                                />
                                <span class="house-room">{{ house.room }}</span>
                                <div v-if="house.roomId" class="house-status">
                                  <IconifyIconOffline
                                    :icon="getStatusIcon(house.status)"
                                    :class="getStatusIconClass(house.status)"
                                  />
                                </div>
                                <div class="house-status-text">
                                  {{ getStatusText(house.status) }}
                                </div>
                              </div>
                            </div>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建楼栋对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建楼栋"
      width="600px"
      :before-close="closeCreateDialog"
    >
      <el-form
        ref="createFormRef"
        :model="createForm"
        :rules="createFormRules"
        label-width="100px"
      >
        <el-form-item label="楼栋类型" prop="buildingtypeId">
          <el-select
            v-model="createForm.buildingtypeId"
            placeholder="请选择楼栋类型"
            style="width: 100%"
          >
            <el-option
              v-for="type in buildingTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼栋名称" prop="name">
          <el-input
            v-model="createForm.name"
            placeholder="请输入楼栋名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="楼宇朝向" prop="orientation">
          <el-select
            v-model="createForm.orientation"
            placeholder="请选择楼宇朝向"
            style="width: 100%"
          >
            <el-option
              v-for="option in orientationOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼高(米)" prop="heightM">
          <el-input-number
            v-model="createForm.heightM"
            :min="1"
            :max="999"
            placeholder="请输入楼高"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇结构" prop="structure">
          <el-input
            v-model="createForm.structure"
            placeholder="请输入楼宇结构"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="单元数" prop="unitCount">
          <el-input-number
            v-model="createForm.unitCount"
            :min="1"
            :max="20"
            placeholder="请输入单元数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼层数" prop="floorCount">
          <el-input-number
            v-model="createForm.floorCount"
            :min="1"
            :max="100"
            placeholder="请输入楼层数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCreateDialog">取消</el-button>
          <el-button type="primary" @click="submitCreateBuilding">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑楼栋对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑楼栋"
      width="600px"
      :before-close="closeEditDialog"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="楼栋名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入楼栋名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="楼宇朝向" prop="orientation">
          <el-select
            v-model="editForm.orientation"
            placeholder="请选择楼宇朝向"
            style="width: 100%"
          >
            <el-option
              v-for="option in orientationOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼高(米)" prop="heightM">
          <el-input-number
            v-model="editForm.heightM"
            :min="1"
            :max="999"
            placeholder="请输入楼高"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼宇结构" prop="structure">
          <el-input
            v-model="editForm.structure"
            placeholder="请输入楼宇结构"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="单元数" prop="unitCount">
          <el-input-number
            v-model="editForm.unitCount"
            :min="1"
            :max="20"
            placeholder="请输入单元数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="楼层数" prop="floorCount">
          <el-input-number
            v-model="editForm.floorCount"
            :min="1"
            :max="100"
            placeholder="请输入楼层数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditDialog">取消</el-button>
          <el-button type="primary" @click="submitEditBuilding">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加房屋对话框 -->
    <el-dialog
      v-model="showAddHouseDialog"
      title="添加房屋"
      width="600px"
      :before-close="closeAddHouseDialog"
    >
      <el-form
        ref="addHouseFormRef"
        :model="addHouseForm"
        :rules="addHouseFormRules"
        label-width="100px"
      >
        <el-form-item label="单元" prop="unitId">
          <el-select
            v-model="addHouseForm.unitId"
            placeholder="请选择单元"
            style="width: 100%"
          >
            <el-option
              v-for="unit in unitOptions"
              :key="unit.id"
              :label="unit.name"
              :value="unit.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="楼层" prop="floorId">
          <el-select
            v-model="addHouseForm.floorId"
            placeholder="请选择楼层"
            style="width: 100%"
          >
            <el-option
              v-for="floor in floorOptions"
              :key="floor.id"
              :label="floor.name"
              :value="floor.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="房屋编号" prop="houseNum">
          <el-input-number
            v-model="addHouseForm.houseNum"
            :min="1"
            placeholder="请输入房屋编号"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="房屋朝向" prop="orientation">
          <el-select
            v-model="addHouseForm.orientation"
            placeholder="请选择房屋朝向"
            style="width: 100%"
          >
            <el-option
              v-for="option in orientationOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="建筑面积" prop="floorSpace">
          <el-input
            v-model="addHouseForm.floorSpace"
            placeholder="请输入建筑面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="套内面积" prop="insideSpace">
          <el-input
            v-model="addHouseForm.insideSpace"
            placeholder="请输入套内面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="公摊面积" prop="sharedSpace">
          <el-input
            v-model="addHouseForm.sharedSpace"
            placeholder="请输入公摊面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="房间数" prop="room">
          <el-input-number
            v-model="addHouseForm.room"
            :min="1"
            placeholder="请输入房间数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="客厅数" prop="hall">
          <el-input-number
            v-model="addHouseForm.hall"
            :min="0"
            placeholder="请输入客厅数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="卫生间数" prop="toilet">
          <el-input-number
            v-model="addHouseForm.toilet"
            :min="0"
            placeholder="请输入卫生间数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeAddHouseDialog">取消</el-button>
          <el-button type="primary" @click="submitAddHouse">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 房屋详情对话框 -->
    <el-dialog
      v-model="showHouseDetailDialog"
      title="房屋详情"
      width="600px"
      :before-close="closeHouseDetailDialog"
    >
      <div v-if="houseDetail" class="house-detail-content">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">房屋编号:</span>
              <span class="value">{{ houseDetail.number }}</span>
            </div>
            <div class="detail-item">
              <span class="label">房屋朝向:</span>
              <span class="value">{{
                houseDetail.orientation || "未设置"
              }}</span>
            </div>
            <div class="detail-item">
              <span class="label">建筑面积:</span>
              <span class="value">{{ houseDetail.floorSpace }}㎡</span>
            </div>
            <div class="detail-item">
              <span class="label">套内面积:</span>
              <span class="value"
                >{{ houseDetail.insideSpace || "未设置" }}㎡</span
              >
            </div>
            <div class="detail-item">
              <span class="label">公摊面积:</span>
              <span class="value"
                >{{ houseDetail.sharedSpace || "未设置" }}㎡</span
              >
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>房间配置</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">房间数:</span>
              <span class="value">{{ houseDetail.room }}间</span>
            </div>
            <div class="detail-item">
              <span class="label">客厅数:</span>
              <span class="value">{{ houseDetail.hall }}间</span>
            </div>
            <div class="detail-item">
              <span class="label">卫生间数:</span>
              <span class="value">{{ houseDetail.toilet }}间</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>时间信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ houseDetail.createTime }}</span>
            </div>
            <div class="detail-item">
              <span class="label">更新时间:</span>
              <span class="value">{{ houseDetail.updateTime }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>入住人员信息</h4>
          <div v-if="personnelLoading" class="detail-grid">
            <div class="detail-item">
              <span class="label">加载中...</span>
            </div>
          </div>
          <div v-else-if="!personnelInfo" class="detail-grid">
            <div class="detail-item">
              <span class="label">入住人员:</span>
              <span class="value">暂无入住人员信息</span>
            </div>
          </div>
          <div v-else class="detail-grid">
            <div class="detail-item">
              <span class="label">类型:</span>
              <span class="value">
                <el-tag :type="personnelInfo.payerType === 1 ? 'success' : 'info'">
                  {{ personnelInfo.payerType === 1 ? '业主' : '租户' }}
                </el-tag>
              </span>
            </div>
            <div class="detail-item">
              <span class="label">姓名:</span>
              <span class="value">{{ personnelInfo.name }}</span>
            </div>
            <div class="detail-item">
              <span class="label">手机号:</span>
              <span class="value">{{ personnelInfo.phone }}</span>
            </div>
            <div class="detail-item">
              <span class="label">邮箱:</span>
              <span class="value">{{ personnelInfo.email }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeHouseDetailDialog">关闭</el-button>
          <el-button type="primary" @click="openEditHouseDialog"
            >修改</el-button
          >
          <el-button 
            type="warning" 
            :disabled="!!personnelInfo"
            @click="openBindOwnerDialog"
          >
            绑定业主信息
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑房屋对话框 -->
    <el-dialog
      v-model="showEditHouseDialog"
      title="编辑房屋"
      width="600px"
      :before-close="closeEditHouseDialog"
    >
      <el-form
        ref="editHouseFormRef"
        :model="editHouseForm"
        :rules="editHouseFormRules"
        label-width="100px"
      >
        <el-form-item label="房屋编号" prop="houseNum">
          <el-input-number
            v-model="editHouseForm.houseNum"
            :min="1"
            placeholder="请输入房屋编号"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="建筑面积" prop="floorSpace">
          <el-input
            v-model="editHouseForm.floorSpace"
            placeholder="请输入建筑面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="套内面积" prop="insideSpace">
          <el-input
            v-model="editHouseForm.insideSpace"
            placeholder="请输入套内面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="公摊面积" prop="sharedSpace">
          <el-input
            v-model="editHouseForm.sharedSpace"
            placeholder="请输入公摊面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="房间数" prop="room">
          <el-input-number
            v-model="editHouseForm.room"
            :min="1"
            placeholder="请输入房间数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="客厅数" prop="hall">
          <el-input-number
            v-model="editHouseForm.hall"
            :min="0"
            placeholder="请输入客厅数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="卫生间数" prop="toilet">
          <el-input-number
            v-model="editHouseForm.toilet"
            :min="0"
            placeholder="请输入卫生间数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeEditHouseDialog">取消</el-button>
          <el-button type="primary" @click="submitEditHouse">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 绑定业主信息对话框 -->
    <el-dialog
      v-model="showBindOwnerDialog"
      title="绑定业主信息"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      class="fullscreen-dialog"
    >
      <!-- 功能说明 -->
      <div class="function-description">
        <ol>
          <li>为房屋绑定业主信息，支持搜索现有业主或创建新业主；</li>
          <li>如果业主已存在，直接选择并绑定到房屋；</li>
          <li>如果业主不存在，可以创建新业主并自动绑定到房屋。</li>
        </ol>
      </div>

      <el-form
        ref="bindOwnerFormRef"
        :model="bindOwnerForm"
        :rules="bindOwnerFormRules"
        label-width="100px"
        class="owner-form"
      >
        <!-- 房屋信息 -->
        <div class="form-section">
          <h3 class="section-title">房屋信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="房屋编号">
                <el-input :value="houseDetail?.number" disabled />
              </el-form-item>
              <el-form-item label="建筑面积">
                <el-input :value="houseDetail?.floorSpace + '㎡'" disabled />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 业主选择方式 -->
        <div class="form-section">
          <h3 class="section-title">业主选择方式</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="选择方式" prop="bindType">
                <el-radio-group v-model="bindOwnerForm.bindType">
                  <el-radio :value="1">搜索现有业主</el-radio>
                  <el-radio :value="2">创建新业主</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 搜索现有业主 -->
        <div v-if="bindOwnerForm.bindType === 1" class="form-section">
          <h3 class="section-title">搜索现有业主</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="业主姓名" prop="searchOwnerName">
                <el-input
                  v-model="bindOwnerForm.searchOwnerName"
                  placeholder="请输入业主姓名"
                  @input="searchOwners"
                />
              </el-form-item>
              <el-form-item label="手机号" prop="searchPhone">
                <el-input
                  v-model="bindOwnerForm.searchPhone"
                  placeholder="请输入手机号"
                  @input="searchOwners"
                />
              </el-form-item>
              <el-form-item label="选择业主" prop="selectedOwnerId">
                <el-select
                  v-model="bindOwnerForm.selectedOwnerId"
                  placeholder="请选择业主"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="owner in searchOwnerList"
                    :key="owner.id"
                    :label="`${owner.ownerName} - ${owner.phone}`"
                    :value="owner.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 创建新业主 -->
        <div v-if="bindOwnerForm.bindType === 2" class="form-section">
          <h3 class="section-title">创建新业主</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="姓名" prop="ownerName">
                <el-input v-model="bindOwnerForm.ownerName" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="bindOwnerForm.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="手机号" prop="phone">
                <el-input v-model="bindOwnerForm.phone" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="bindOwnerForm.email" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="身份证号" prop="idCard">
                <el-input v-model="bindOwnerForm.idCard" placeholder="请输入" />
              </el-form-item>

              <el-form-item label="住户身份" prop="residentType">
                <el-select v-model="bindOwnerForm.residentType" placeholder="请选择住户身份" style="width: 100%">
                  <el-option label="业主" :value="1" />
                  <el-option label="子女" :value="2" />
                  <el-option label="亲戚" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>

              <el-form-item label="入住时间" prop="moveInTime">
                <el-date-picker
                  v-model="bindOwnerForm.moveInTime"
                  type="datetime"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="bindOwnerForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>

      <template #footer>
        <el-button @click="closeBindOwnerDialog">取消</el-button>
        <el-button type="primary" @click="submitBindOwner">确定绑定</el-button>
      </template>
    </el-dialog>

    <!-- 生成所有房屋对话框 -->
    <el-dialog
      v-model="showGenerateHousesDialog"
      title="生成所有房屋"
      width="600px"
      :before-close="closeGenerateHousesDialog"
    >
      <el-form
        ref="generateHousesFormRef"
        :model="generateHousesForm"
        :rules="generateHousesFormRules"
        label-width="120px"
      >
        <el-form-item label="每单元房屋数" prop="houseNumberOFUnits">
          <el-input-number
            v-model="generateHousesForm.houseNumberOFUnits"
            :min="1"
            :max="20"
            placeholder="请输入每单元房屋数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="房屋朝向" prop="orientation">
          <el-select
            v-model="generateHousesForm.orientation"
            placeholder="请选择房屋朝向"
            style="width: 100%"
          >
            <el-option
              v-for="option in orientationOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="建筑面积" prop="floorSpace">
          <el-input
            v-model="generateHousesForm.floorSpace"
            placeholder="请输入建筑面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="套内面积" prop="insideSpace">
          <el-input
            v-model="generateHousesForm.insideSpace"
            placeholder="请输入套内面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="公摊面积" prop="sharedSpace">
          <el-input
            v-model="generateHousesForm.sharedSpace"
            placeholder="请输入公摊面积"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="房间数" prop="room">
          <el-input-number
            v-model="generateHousesForm.room"
            :min="1"
            placeholder="请输入房间数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="客厅数" prop="hall">
          <el-input-number
            v-model="generateHousesForm.hall"
            :min="0"
            placeholder="请输入客厅数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="卫生间数" prop="toilet">
          <el-input-number
            v-model="generateHousesForm.toilet"
            :min="0"
            placeholder="请输入卫生间数"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeGenerateHousesDialog">取消</el-button>
          <el-button type="primary" @click="submitGenerateHouses"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCommunityList, type CommunityItem } from "@/api/community";
import {
  getBuildingTypeList,
  getBuildingList,
  getHouseManagement,
  getUnitList,
  getFloorList,
  addHouse,
  deleteHouse,
  updateHouse,
  getHouseDetail,
  queryPersonnelByHouseId,
  createBuilding,
  updateBuilding,
  deleteBuilding,
  deleteAllHouses as deleteAllHousesApi,
  generateAllHouses as generateAllHousesApi,
  type BuildingType,
  type BuildingItem,
  type HouseItem,
  type BuildingCreateParams,
  type BuildingUpdateParams,
  type HouseManagementData,
  type UnitItem,
  type FloorItem,
  type HouseAddParams,
  type HouseUpdateParams,
  type HouseDetail,
  type PersonnelItem,
  type GenerateAllHousesParams
} from "@/api/building";
import {
  getOwnerList,
  createOwner,
  moveInOwner,
  type Owner,
  type OwnerQueryParams,
  type CreateOwnerRequest
} from "@/api/owner";

defineOptions({ name: "DataCenterBuilding" });

// 响应式数据
const communityList = ref<CommunityItem[]>([]);
const selectedCommunityId = ref<number | null>(null);
const selectedCommunityName = ref<string>("");
const selectedCommunityAddress = ref<string>("");

// 楼栋相关数据
const buildingTypes = ref<BuildingType[]>([]);
const buildingList = ref<BuildingItem[]>([]);
const activeType = ref<string>("");
const selectedBuildingId = ref<number | null>(null);
const selectedBuilding = ref<BuildingItem | null>(null);

// 房屋相关数据
const houseList = ref<HouseItem[]>([]);
const unitList = ref<string[]>([]);
const floorList = ref<string[]>([]);
const selectedHouses = ref<number[]>([]);

// 添加房屋相关数据
const showAddHouseDialog = ref(false);
const unitOptions = ref<UnitItem[]>([]);
const floorOptions = ref<FloorItem[]>([]);
const addHouseForm = ref<HouseAddParams>({
  unitId: 0,
  floorId: 0,
  houseNum: 0,
  orientation: "",
  floorSpace: "",
  insideSpace: "",
  sharedSpace: "",
  room: 0,
  hall: 0,
  toilet: 0
});
const addHouseFormRef = ref();

// 编辑房屋相关数据
const showEditHouseDialog = ref(false);
const editHouseForm = ref<HouseUpdateParams>({
  id: 0,
  houseNum: 0,
  floorSpace: "",
  insideSpace: "",
  sharedSpace: "",
  room: 0,
  hall: 0,
  toilet: 0
});
const editHouseFormRef = ref();

// 房屋详情相关数据
const showHouseDetailDialog = ref(false);
const houseDetail = ref<HouseDetail | null>(null);
const personnelInfo = ref<PersonnelItem | null>(null);
const personnelLoading = ref(false);

// 生成所有房屋相关数据
const showGenerateHousesDialog = ref(false);
const generateHousesForm = ref<GenerateAllHousesParams>({
  buildingId: 0,
  houseNumberOFUnits: 0,
  orientation: "",
  floorSpace: "",
  insideSpace: "",
  sharedSpace: "",
  room: 0,
  hall: 0,
  toilet: 0
});
const generateHousesFormRef = ref();

// 绑定业主信息相关数据
const showBindOwnerDialog = ref(false);
const bindOwnerForm = ref({
  bindType: 1, // 1: 搜索现有业主, 2: 创建新业主
  searchOwnerName: "",
  searchPhone: "",
  selectedOwnerId: undefined as number | undefined,
  ownerName: "",
  gender: 1,
  phone: "",
  email: "",
  idCard: "",
  residentType: 1,
  moveInTime: "",
  remark: ""
});
const bindOwnerFormRef = ref();
const searchOwnerList = ref<Owner[]>([]);

// 房屋朝向选项
const orientationOptions = [
  { label: "东", value: "东" },
  { label: "南", value: "南" },
  { label: "西", value: "西" },
  { label: "北", value: "北" },
  { label: "东南", value: "东南" },
  { label: "东北", value: "东北" },
  { label: "西南", value: "西南" },
  { label: "西北", value: "西北" }
];

// 创建楼栋相关数据
const showCreateDialog = ref(false);
const createForm = ref<BuildingCreateParams>({
  buildingtypeId: 0,
  name: "",
  orientation: "",
  heightM: 0,
  structure: "",
  unitCount: 0,
  floorCount: 0
});
const createFormRef = ref();

// 编辑楼栋相关数据
const showEditDialog = ref(false);
const editForm = ref<BuildingUpdateParams>({
  id: 0,
  name: "",
  orientation: "",
  heightM: 0,
  structure: "",
  unitCount: 0,
  floorCount: 0
});
const editFormRef = ref();

// 表单验证规则
const createFormRules = {
  buildingtypeId: [
    { required: true, message: "请选择楼栋类型", trigger: "change" }
  ],
  name: [
    { required: true, message: "请输入楼栋名称", trigger: "blur" },
    { min: 1, max: 50, message: "楼栋名称长度在1到50个字符", trigger: "blur" }
  ],
  heightM: [
    { required: true, message: "请输入楼高", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 999,
      message: "楼高必须在1-999米之间",
      trigger: "blur"
    }
  ],
  unitCount: [
    { required: true, message: "请输入单元数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 20,
      message: "单元数必须在1-20之间",
      trigger: "blur"
    }
  ],
  floorCount: [
    { required: true, message: "请输入楼层数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 100,
      message: "楼层数必须在1-100之间",
      trigger: "blur"
    }
  ]
};

// 添加房屋表单验证规则
const addHouseFormRules = {
  unitId: [{ required: true, message: "请选择单元", trigger: "change" }],
  floorId: [{ required: true, message: "请选择楼层", trigger: "change" }],
  houseNum: [
    { required: true, message: "请输入房屋编号", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      message: "房屋编号必须大于0",
      trigger: "blur"
    }
  ],
  orientation: [
    { required: true, message: "请选择房屋朝向", trigger: "change" }
  ],
  floorSpace: [{ required: true, message: "请输入建筑面积", trigger: "blur" }],
  insideSpace: [{ required: true, message: "请输入套内面积", trigger: "blur" }],
  sharedSpace: [{ required: true, message: "请输入公摊面积", trigger: "blur" }],
  room: [
    { required: true, message: "请输入房间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      message: "房间数必须大于0",
      trigger: "blur"
    }
  ],
  hall: [
    { required: true, message: "请输入客厅数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "客厅数不能小于0",
      trigger: "blur"
    }
  ],
  toilet: [
    { required: true, message: "请输入卫生间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "卫生间数不能小于0",
      trigger: "blur"
    }
  ]
};

// 编辑房屋表单验证规则
const editHouseFormRules = {
  houseNum: [
    { required: true, message: "请输入房屋编号", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      message: "房屋编号必须大于0",
      trigger: "blur"
    }
  ],
  floorSpace: [{ required: true, message: "请输入建筑面积", trigger: "blur" }],
  insideSpace: [{ required: true, message: "请输入套内面积", trigger: "blur" }],
  sharedSpace: [{ required: true, message: "请输入公摊面积", trigger: "blur" }],
  room: [
    { required: true, message: "请输入房间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      message: "房间数必须大于0",
      trigger: "blur"
    }
  ],
  hall: [
    { required: true, message: "请输入客厅数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "客厅数不能小于0",
      trigger: "blur"
    }
  ],
  toilet: [
    { required: true, message: "请输入卫生间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "卫生间数不能小于0",
      trigger: "blur"
    }
  ]
};

// 生成所有房屋表单验证规则
const generateHousesFormRules = {
  houseNumberOFUnits: [
    { required: true, message: "请输入每单元房屋数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 20,
      message: "每单元房屋数必须在1-20之间",
      trigger: "blur"
    }
  ],
  orientation: [
    { required: true, message: "请选择房屋朝向", trigger: "change" }
  ],
  floorSpace: [{ required: true, message: "请输入建筑面积", trigger: "blur" }],
  insideSpace: [{ required: true, message: "请输入套内面积", trigger: "blur" }],
  sharedSpace: [{ required: true, message: "请输入公摊面积", trigger: "blur" }],
  room: [
    { required: true, message: "请输入房间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      message: "房间数必须大于0",
      trigger: "blur"
    }
  ],
  hall: [
    { required: true, message: "请输入客厅数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "客厅数不能小于0",
      trigger: "blur"
    }
  ],
  toilet: [
    { required: true, message: "请输入卫生间数", trigger: "blur" },
    {
      type: "number" as const,
      min: 0,
      message: "卫生间数不能小于0",
      trigger: "blur"
    }
  ]
};

// 编辑表单验证规则
const editFormRules = {
  name: [
    { required: true, message: "请输入楼栋名称", trigger: "blur" },
    { min: 1, max: 50, message: "楼栋名称长度在1到50个字符", trigger: "blur" }
  ],
  heightM: [
    { required: true, message: "请输入楼高", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 999,
      message: "楼高必须在1-999米之间",
      trigger: "blur"
    }
  ],
  unitCount: [
    { required: true, message: "请输入单元数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 20,
      message: "单元数必须在1-20之间",
      trigger: "blur"
    }
  ],
  floorCount: [
    { required: true, message: "请输入楼层数", trigger: "blur" },
    {
      type: "number" as const,
      min: 1,
      max: 100,
      message: "楼层数必须在1-100之间",
      trigger: "blur"
    }
  ]
};

// 绑定业主信息表单验证规则
const bindOwnerFormRules = {
  bindType: [{ required: true, message: "请选择绑定方式", trigger: "change" }],
  selectedOwnerId: [
    { required: true, message: "请选择业主", trigger: "change" }
  ],
  ownerName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  email: [
    { type: "email" as const, message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号", trigger: "blur" }
  ],
  moveInTime: [{ required: true, message: "请选择入住时间", trigger: "change" }],
  residentType: [{ required: true, message: "请选择住户身份", trigger: "change" }]
};

// 获取小区列表
const fetchCommunityList = async () => {
  try {
    const response = await getCommunityList();
    if (response.code === 0) {
      communityList.value = response.data;
      // 自动选择第一个小区
      if (response.data.length > 0) {
        const firstCommunity = response.data[0];
        selectedCommunityId.value = firstCommunity.id;
        selectedCommunityName.value = firstCommunity.name;
        selectedCommunityAddress.value = firstCommunity.address;
        // 获取该小区的楼栋类型列表
        fetchBuildingTypes(firstCommunity.id);
      }
    }
  } catch (error) {
    console.error("获取小区列表失败:", error);
  }
};

// 获取楼栋类型列表
const fetchBuildingTypes = async (communityId: number) => {
  console.log("正在获取楼栋类型列表，小区ID:", communityId);
  try {
    const response = await getBuildingTypeList(communityId);
    console.log("楼栋类型响应:", response);
    if (response.code === 0) {
      buildingTypes.value = response.data;
      console.log("楼栋类型数据:", buildingTypes.value);
      // 设置默认选中第一个类型并自动加载楼栋列表
      if (response.data.length > 0) {
        activeType.value = response.data[0].name;
        console.log("设置默认楼栋类型:", activeType.value);
        // 自动加载第一个楼栋类型的楼栋列表
        fetchBuildingList(response.data[0].id);
      }
    }
  } catch (error) {
    console.error("获取楼栋类型失败:", error);
  }
};

// 获取楼栋列表
const fetchBuildingList = async (buildingtypeId: number) => {
  console.log("正在获取楼栋列表，楼栋类型ID:", buildingtypeId);
  try {
    const response = await getBuildingList(buildingtypeId);
    console.log("楼栋列表响应:", response);
    if (response.code === 0) {
      buildingList.value = response.data;
      console.log("楼栋列表数据:", buildingList.value);
    }
  } catch (error) {
    console.error("获取楼栋列表失败:", error);
  }
};

// 获取房屋数据
const fetchHouseData = async (buildingId: number) => {
  console.log("正在获取房屋数据，楼栋ID:", buildingId);
  try {
    const response = await getHouseManagement(buildingId);
    console.log("房屋数据响应:", response);
    if (response.code === 0) {
      // 更新房屋列表、单元列表和楼层列表
      houseList.value = response.data.roomList || [];
      unitList.value = response.data.unitList || [];
      floorList.value = response.data.floorList || [];
      console.log("房屋数据:", houseList.value);
      console.log("单元列表:", unitList.value);
      console.log("楼层列表:", floorList.value);
    }
  } catch (error) {
    console.error("获取房屋数据失败:", error);
  }
};

// 获取单元选项
const fetchUnitOptions = async (buildingId: number) => {
  try {
    const response = await getUnitList(buildingId);
    if (response.code === 0) {
      unitOptions.value = response.data;
    }
  } catch (error) {
    console.error("获取单元列表失败:", error);
  }
};

// 获取楼层选项
const fetchFloorOptions = async (buildingId: number) => {
  try {
    const response = await getFloorList(buildingId);
    if (response.code === 0) {
      floorOptions.value = response.data;
    }
  } catch (error) {
    console.error("获取楼层列表失败:", error);
  }
};

// 处理小区选择变化
const handleCommunityChange = (communityId: number | null) => {
  selectedCommunityId.value = communityId;

  if (communityId) {
    const selectedCommunity = communityList.value.find(
      community => community.id === communityId
    );
    if (selectedCommunity) {
      selectedCommunityName.value = selectedCommunity.name;
      selectedCommunityAddress.value = selectedCommunity.address;
      // 获取该小区的楼栋类型列表
      fetchBuildingTypes(communityId);
    }
  } else {
    selectedCommunityName.value = "";
    selectedCommunityAddress.value = "";
    buildingTypes.value = [];
    buildingList.value = [];
    activeType.value = "";
  }

  console.log(
    "选择的小区:",
    selectedCommunityName.value,
    selectedCommunityAddress.value
  );
};

// 处理楼栋类型切换
const handleTypeChange = (typeName: string) => {
  activeType.value = typeName;
  // 找到对应的楼栋类型ID
  const selectedType = buildingTypes.value.find(type => type.name === typeName);
  if (selectedType) {
    fetchBuildingList(selectedType.id);
  }
  // 清空选中的楼栋
  selectedBuildingId.value = null;
  selectedBuilding.value = null;
};

// 选择楼栋
const selectBuilding = (building: BuildingItem) => {
  selectedBuildingId.value = building.id;
  selectedBuilding.value = building;
  console.log("选择楼栋:", building);
  // 获取该楼栋的房屋数据
  fetchHouseData(building.id);
  // 获取单元和楼层选项
  fetchUnitOptions(building.id);
  fetchFloorOptions(building.id);
};

// 处理房屋选择
const handleHouseSelect = (room: number) => {
  // 根据房屋编号找到对应的房屋ID
  const house = houseList.value.find(h => h.room === room);
  if (!house || !house.roomId) {
    console.warn("未找到房屋ID:", room);
    return;
  }
  const houseId = house.roomId;
  const index = selectedHouses.value.indexOf(houseId);
  if (index > -1) {
    selectedHouses.value.splice(index, 1);
  } else {
    selectedHouses.value.push(houseId);
  }
};

// 获取所有单元
const getUnits = () => {
  return unitList.value;
};

// 获取所有楼层
const getFloors = () => {
  return floorList.value;
};

// 获取指定单元和楼层的房屋
const getHousesByUnitAndFloor = (unit: string, floor: string) => {
  return houseList.value.filter(
    house => house.unit === unit && house.floor === floor
  );
};

// 打开创建楼栋对话框
const openCreateDialog = () => {
  if (!selectedCommunityId.value) {
    ElMessage.warning("请先选择小区");
    return;
  }
  if (buildingTypes.value.length === 0) {
    ElMessage.warning("该小区暂无楼栋类型");
    return;
  }

  // 动态绑定当前选中的楼栋类型
  let defaultBuildingTypeId = buildingTypes.value[0].id;
  if (activeType.value) {
    const currentType = buildingTypes.value.find(
      type => type.name === activeType.value
    );
    if (currentType) {
      defaultBuildingTypeId = currentType.id;
    }
  }

  // 重置表单
  createForm.value = {
    buildingtypeId: defaultBuildingTypeId,
    name: "",
    orientation: "",
    heightM: 0,
    structure: "",
    unitCount: 0,
    floorCount: 0
  };
  showCreateDialog.value = true;
};

// 关闭创建楼栋对话框
const closeCreateDialog = () => {
  showCreateDialog.value = false;
  createFormRef.value?.resetFields();
};

// 关闭编辑楼栋对话框
const closeEditDialog = () => {
  showEditDialog.value = false;
  editFormRef.value?.resetFields();
};

// 提交创建楼栋表单
const submitCreateBuilding = async () => {
  if (!createFormRef.value) return;

  try {
    await createFormRef.value.validate();

    const response = await createBuilding(createForm.value);
    if (response.code === 0) {
      ElMessage.success("楼栋创建成功");
      closeCreateDialog();
      // 刷新楼栋列表
      const currentType = buildingTypes.value.find(
        type => type.id === createForm.value.buildingtypeId
      );
      if (currentType) {
        fetchBuildingList(currentType.id);
      }
    } else {
      ElMessage.error(response.message || "创建失败");
    }
  } catch (error) {
    console.error("创建楼栋失败:", error);
    ElMessage.error("创建失败，请检查表单信息");
  }
};

// 提交编辑楼栋表单
const submitEditBuilding = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();

    const response = await updateBuilding(editForm.value);
    if (response.code === 0) {
      ElMessage.success("楼栋修改成功");
      closeEditDialog();

      // 如果修改的是当前选中的楼栋，更新选中状态
      if (selectedBuildingId.value === editForm.value.id) {
        selectedBuilding.value = {
          ...selectedBuilding.value!,
          name: editForm.value.name,
          orientation: editForm.value.orientation,
          heightM: editForm.value.heightM,
          structure: editForm.value.structure,
          unitCount: editForm.value.unitCount,
          floorCount: editForm.value.floorCount
        };
      }

      // 刷新楼栋列表
      const currentType = buildingTypes.value.find(
        type => type.name === activeType.value
      );
      if (currentType) {
        fetchBuildingList(currentType.id);
      }
    } else {
      ElMessage.error(response.message || "修改失败");
    }
  } catch (error) {
    console.error("修改楼栋失败:", error);
    ElMessage.error("修改失败，请检查表单信息");
  }
};

// 处理楼栋编辑
const handleBuildingEdit = (building: BuildingItem) => {
  // 填充编辑表单数据
  editForm.value = {
    id: building.id,
    name: building.name,
    orientation: building.orientation || "",
    heightM: building.heightM,
    structure: building.structure || "",
    unitCount: building.unitCount,
    floorCount: building.floorCount
  };
  showEditDialog.value = true;
};

// 处理楼栋删除
const handleBuildingDelete = async (building: BuildingItem) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除楼栋"${building.name}"吗？删除后无法恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger"
      }
    );

    // 执行删除操作
    const response = await deleteBuilding(building.id);
    if (response.code === 0) {
      ElMessage.success("楼栋删除成功");

      // 如果删除的是当前选中的楼栋，清空选中状态
      if (selectedBuildingId.value === building.id) {
        selectedBuildingId.value = null;
        selectedBuilding.value = null;
        houseList.value = [];
        unitList.value = [];
        floorList.value = [];
      }

      // 刷新楼栋列表
      const currentType = buildingTypes.value.find(
        type => type.name === activeType.value
      );
      if (currentType) {
        fetchBuildingList(currentType.id);
      }
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除楼栋失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
};

// 打开添加房屋对话框
const openAddHouseDialog = () => {
  if (!selectedBuildingId.value) {
    ElMessage.warning("请先选择楼栋");
    return;
  }
  // 重置表单
  addHouseForm.value = {
    unitId: 0,
    floorId: 0,
    houseNum: 0,
    orientation: "",
    floorSpace: "",
    insideSpace: "",
    sharedSpace: "",
    room: 0,
    hall: 0,
    toilet: 0
  };
  showAddHouseDialog.value = true;
};

// 关闭添加房屋对话框
const closeAddHouseDialog = () => {
  showAddHouseDialog.value = false;
  addHouseFormRef.value?.resetFields();
};

// 提交添加房屋表单
const submitAddHouse = async () => {
  if (!addHouseFormRef.value) return;

  try {
    await addHouseFormRef.value.validate();

    const response = await addHouse(addHouseForm.value);
    if (response.code === 0) {
      ElMessage.success("房屋添加成功");
      closeAddHouseDialog();
      // 刷新房屋数据
      if (selectedBuildingId.value) {
        fetchHouseData(selectedBuildingId.value);
      }
    } else {
      ElMessage.error(response.message || "添加失败");
    }
  } catch (error) {
    console.error("添加房屋失败:", error);
    ElMessage.error("添加失败，请检查表单信息");
  }
};

// 删除选中的房屋
const deleteSelectedHouses = async () => {
  if (selectedHouses.value.length === 0) {
    ElMessage.warning("请先选择要删除的房屋");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHouses.value.length} 个房屋吗？删除后无法恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger"
      }
    );

    const response = await deleteHouse(selectedHouses.value);
    if (response.code === 0) {
      ElMessage.success("房屋删除成功");
      // 清空选中状态
      selectedHouses.value = [];
      // 刷新房屋数据
      if (selectedBuildingId.value) {
        fetchHouseData(selectedBuildingId.value);
      }
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除房屋失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
};

// 打开房屋详情对话框
const openHouseDetailDialog = async () => {
  if (selectedHouses.value.length !== 1) {
    ElMessage.warning("请选择一个房屋查看详情");
    return;
  }

  try {
    const houseId = selectedHouses.value[0];
    const response = await getHouseDetail(houseId);
    if (response.code === 0) {
      houseDetail.value = response.data;
      showHouseDetailDialog.value = true;
      // 详情打开后获取入住人员
      fetchPersonnelInfo();
    } else {
      ElMessage.error(response.message || "获取房屋详情失败");
    }
  } catch (error) {
    console.error("获取房屋详情失败:", error);
    ElMessage.error("获取房屋详情失败，请稍后重试");
  }
};

// 关闭房屋详情对话框
const closeHouseDetailDialog = () => {
  showHouseDetailDialog.value = false;
  houseDetail.value = null;
  personnelInfo.value = null;
};

// 打开编辑房屋对话框
const openEditHouseDialog = () => {
  if (!houseDetail.value) {
    ElMessage.warning("房屋详情数据不存在");
    return;
  }
  // 填充编辑表单数据
  editHouseForm.value = {
    id: houseDetail.value.id,
    houseNum: houseDetail.value.number,
    floorSpace: houseDetail.value.floorSpace,
    insideSpace: houseDetail.value.insideSpace || "",
    sharedSpace: houseDetail.value.sharedSpace || "",
    room: houseDetail.value.room,
    hall: houseDetail.value.hall,
    toilet: houseDetail.value.toilet
  };
  showEditHouseDialog.value = true;
};

// 打开绑定业主信息对话框
const openBindOwnerDialog = () => {
  if (!houseDetail.value) {
    ElMessage.warning("房屋详情数据不存在");
    return;
  }
  
  // 检查是否已有入住人员信息
  if (personnelInfo.value) {
    ElMessage.warning("该房屋已有入住人员信息，无法重复绑定业主信息");
    return;
  }
  
  // 重置表单
  bindOwnerForm.value = {
    bindType: 1,
    searchOwnerName: "",
    searchPhone: "",
    selectedOwnerId: undefined,
    ownerName: "",
    gender: 1,
    phone: "",
    email: "",
    idCard: "",
    residentType: 1,
    moveInTime: "",
    remark: ""
  };
  searchOwnerList.value = [];
  showBindOwnerDialog.value = true;
};

// 关闭绑定业主信息对话框
const closeBindOwnerDialog = () => {
  showBindOwnerDialog.value = false;
  bindOwnerFormRef.value?.resetFields();
};

// 搜索业主
const searchOwners = async () => {
  const { searchOwnerName, searchPhone } = bindOwnerForm.value;
  if (!searchOwnerName && !searchPhone) {
    searchOwnerList.value = [];
    return;
  }

  try {
    const params: OwnerQueryParams = {
      page: 0,
      limit: 50,
      status: 1, // 只搜索已迁入的业主
      ownerName: searchOwnerName || undefined,
      phone: searchPhone || undefined
    };
    
    const response = await getOwnerList(params);
    if (response.code === 0 && response.data) {
      searchOwnerList.value = response.data.list || [];
    } else {
      searchOwnerList.value = [];
    }
  } catch (error) {
    console.error("搜索业主失败:", error);
    searchOwnerList.value = [];
  }
};

// 提交绑定业主信息
const submitBindOwner = async () => {
  if (!bindOwnerFormRef.value) return;

  try {
    await bindOwnerFormRef.value.validate();

    if (!houseDetail.value) {
      ElMessage.error("房屋信息不存在");
      return;
    }

    if (bindOwnerForm.value.bindType === 1) {
      // 选择现有业主
      if (!bindOwnerForm.value.selectedOwnerId) {
        ElMessage.error("请选择业主");
        return;
      }

      // 绑定现有业主到房屋
      const moveInData = {
        ownerId: bindOwnerForm.value.selectedOwnerId,
        houseId: houseDetail.value.id,
        moveInTime: new Date().toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '')
      };

      const response = await moveInOwner(moveInData);
      if (response.code === 0) {
        ElMessage.success("绑定业主信息成功");
        closeBindOwnerDialog();
        // 刷新房屋详情
        if (selectedHouses.value.length > 0) {
          await openHouseDetailDialog();
        }
      } else {
        ElMessage.error(response.message || "绑定失败");
      }
    } else {
      // 创建新业主（自动绑定房屋）
      const createData: CreateOwnerRequest = {
        cellId: selectedCommunityId.value!,
        name: bindOwnerForm.value.ownerName,
        phone: bindOwnerForm.value.phone,
        gender: bindOwnerForm.value.gender,
        email: bindOwnerForm.value.email || "",
        remark: bindOwnerForm.value.remark || "",
        idCard: bindOwnerForm.value.idCard || "",
        moveInTime: bindOwnerForm.value.moveInTime || new Date().toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, ''),
        houseId: houseDetail.value.id,
        residentType: bindOwnerForm.value.residentType
      };

      const createResponse = await createOwner(createData);
      if (createResponse.code === 0) {
        ElMessage.success("创建业主并绑定房屋成功");
        closeBindOwnerDialog();
        // 刷新房屋详情
        if (selectedHouses.value.length > 0) {
          await openHouseDetailDialog();
        }
      } else {
        ElMessage.error(createResponse.message || "创建业主失败");
      }
    }
  } catch (error) {
    console.error("绑定业主信息失败:", error);
    ElMessage.error("绑定失败，请检查表单信息");
  }
};

// 关闭编辑房屋对话框
const closeEditHouseDialog = () => {
  showEditHouseDialog.value = false;
  editHouseFormRef.value?.resetFields();
};

// 提交编辑房屋表单
const submitEditHouse = async () => {
  if (!editHouseFormRef.value) return;

  try {
    await editHouseFormRef.value.validate();

    const response = await updateHouse(editHouseForm.value);
    if (response.code === 0) {
      ElMessage.success("房屋修改成功");
      closeEditHouseDialog();
      // 关闭房屋详情对话框
      closeHouseDetailDialog();
      // 刷新房屋数据
      if (selectedBuildingId.value) {
        fetchHouseData(selectedBuildingId.value);
      }
    } else {
      ElMessage.error(response.message || "修改失败");
    }
  } catch (error) {
    console.error("修改房屋失败:", error);
    ElMessage.error("修改失败，请检查表单信息");
  }
};

// 删除所有房屋
const deleteAllHouses = async () => {
  if (!selectedBuildingId.value) {
    ElMessage.warning("请先选择楼栋");
    return;
  }

  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除楼栋"${selectedBuilding.value?.name}"的所有房屋吗？删除后无法恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "el-button--danger"
      }
    );

    // 执行删除操作
    const response = await deleteAllHousesApi(selectedBuildingId.value);
    if (response.code === 0) {
      ElMessage.success("所有房屋删除成功");
      // 清空选中状态
      selectedHouses.value = [];
      // 刷新房屋数据
      fetchHouseData(selectedBuildingId.value);
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除所有房屋失败:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  }
};

// 打开生成所有房屋对话框
const openGenerateHousesDialog = () => {
  if (!selectedBuildingId.value) {
    ElMessage.warning("请先选择楼栋");
    return;
  }

  // 重置表单
  generateHousesForm.value = {
    buildingId: selectedBuildingId.value,
    houseNumberOFUnits: 0,
    orientation: "",
    floorSpace: "",
    insideSpace: "",
    sharedSpace: "",
    room: 0,
    hall: 0,
    toilet: 0
  };
  showGenerateHousesDialog.value = true;
};

// 关闭生成所有房屋对话框
const closeGenerateHousesDialog = () => {
  showGenerateHousesDialog.value = false;
  generateHousesFormRef.value?.resetFields();
};

// 提交生成所有房屋表单
const submitGenerateHouses = async () => {
  if (!generateHousesFormRef.value) return;

  try {
    await generateHousesFormRef.value.validate();

    const response = await generateAllHousesApi(generateHousesForm.value);
    if (response.code === 0) {
      ElMessage.success("所有房屋生成成功");
      closeGenerateHousesDialog();
      // 刷新房屋数据
      if (selectedBuildingId.value) {
        fetchHouseData(selectedBuildingId.value);
      }
    } else {
      ElMessage.error(response.message || "生成失败");
    }
  } catch (error) {
    console.error("生成所有房屋失败:", error);
    ElMessage.error("生成失败，请检查表单信息");
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCommunityList();
});

// 获取入住人员信息
const fetchPersonnelInfo = async () => {
  if (!houseDetail.value) return;
  personnelLoading.value = true;
  try {
    const payload = {
      ownerId: (houseDetail.value.ownerId ?? null) as number | null,
      renterId: (houseDetail.value.renterId ?? null) as number | null,
      id: houseDetail.value.id
    };
    const res = await queryPersonnelByHouseId(payload);
    if (res.code === 0) {
      personnelInfo.value = res.data;
    } else {
      personnelInfo.value = null;
    }
  } catch (e) {
    personnelInfo.value = null;
  } finally {
    personnelLoading.value = false;
  }
};

// 获取房屋状态图标
const getStatusIcon = (status: number) => {
  switch (status) {
    case 0:
      return "ep:house";
    case 1:
      return "ep:user";
    case 2:
      return "ep:money";
    default:
      return "ep:house";
  }
};

// 获取房屋状态图标样式类
const getStatusIconClass = (status: number) => {
  switch (status) {
    case 0:
      return "status-icon-idle";
    case 1:
      return "status-icon-occupied";
    case 2:
      return "status-icon-rented";
    default:
      return "status-icon-idle";
  }
};

// 获取房屋状态文字
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "闲置";
    case 1:
      return "自用";
    case 2:
      return "出租";
    default:
      return "未知";
  }
};
</script>

<style scoped>
.main {
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  margin-bottom: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.community-selector {
  display: flex;
  align-items: center;
}

.content-area {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  min-height: 400px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 64px;
}

.empty-text {
  margin: 0;
  font-size: 16px;
}

.building-content {
  padding: 20px;
}

.community-info {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.community-name {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.community-address {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.building-management {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.building-types {
  flex: 0 0 300px;
  min-width: 300px;
}

.building-details {
  flex: 1;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.building-list {
  margin-top: 20px;
}

.empty-buildings {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.add-building-btn {
  margin-top: 16px;
}

.generate-houses-btn {
  margin-top: 8px;
}

.building-nav {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.building-nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.nav-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.building-nav-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

.building-nav-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.building-nav-item:last-child {
  border-bottom: none;
}

.building-nav-item:hover {
  background-color: #f8f9fa;
}

.building-nav-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.building-nav-item .building-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.building-nav-item .building-actions {
  display: flex;
  gap: 4px;
}

.building-nav-item .action-btn {
  padding: 4px;
  color: #909399;
  font-size: 16px;
}

.building-nav-item .action-btn:hover {
  color: #409eff;
}

/* 灰色图标样式 */
.building-nav-item .edit-btn {
  color: #909399 !important;
}

.building-nav-item .delete-btn {
  color: #909399 !important;
}

.building-nav-item .edit-btn:hover {
  color: #e6a23c !important;
}

.building-nav-item .delete-btn:hover {
  color: #f56c6c !important;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

/* 右侧楼栋详细信息样式 */
.empty-details {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.building-info-panel {
  padding: 20px;
}

.building-info-header {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.building-title {
  margin: 0 0 16px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.building-basic-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.building-actions-header {
  display: flex;
  gap: 12px;
}

.floors-container {
  margin-top: 20px;
}

.floors-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.floors-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.floors-actions {
  display: flex;
  gap: 8px;
}

.floors-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.floors-placeholder {
  text-align: center;
  color: #909399;
}

.floors-placeholder p {
  margin: 8px 0;
}

/* 房屋网格样式 */
.empty-houses {
  text-align: center;
  color: #909399;
  padding: 40px;
}

.house-grid {
  overflow-x: auto;
}

.house-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
  background: white;
}

.house-table th,
.house-table td {
  border: 1px solid #e4e7ed;
  padding: 8px;
  text-align: center;
  vertical-align: top;
}

.floor-header {
  background: #f8f9fa;
  font-weight: 600;
  color: #303133;
  min-width: 80px;
}

.unit-header {
  background: #f8f9fa;
  font-weight: 600;
  color: #303133;
  min-width: 120px;
}

.floor-cell {
  background: #f8f9fa;
  font-weight: 500;
  color: #606266;
}

.unit-cell {
  background: white;
  min-height: 60px;
}

.houses-in-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
  justify-content: flex-start;
  align-items: center;
  min-height: 40px;
}

.house-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 6px;
  padding: 6px 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 120px;
  justify-content: flex-start;
  position: relative;
}

.house-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.house-item.selected {
  border-color: #409eff;
  background: #ecf5ff;
}

/* 房屋状态样式 */
.house-item.status-idle {
  border-color: #909399;
  background: #f5f7fa;
}

.house-item.status-idle:hover {
  border-color: #909399;
  background: #f0f2f5;
}

.house-item.status-occupied {
  border-color: #67c23a;
  background: #f0f9ff;
}

.house-item.status-occupied:hover {
  border-color: #67c23a;
  background: #e8f5e8;
}

.house-item.status-rented {
  border-color: #e6a23c;
  background: #fdf6ec;
}

.house-item.status-rented:hover {
  border-color: #e6a23c;
  background: #faf2e6;
}

.house-checkbox {
  margin: 0;
}

.house-room {
  font-size: 12px;
  font-weight: 500;
  color: #303133;
}

.house-status {
  position: relative;
  margin-left: 4px;
}

.status-icon {
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.house-status-text {
  font-size: 10px;
  font-weight: 500;
  margin-left: 4px;
  text-align: left;
}

/* 状态图标颜色 */
.status-icon-idle {
  color: #909399;
}

.status-icon-occupied {
  color: #67c23a;
}

.status-icon-rented {
  color: #e6a23c;
}

/* 状态文字颜色 */
.house-item.status-idle .house-status-text {
  color: #909399;
}

.house-item.status-occupied .house-status-text {
  color: #67c23a;
}

.house-item.status-rented .house-status-text {
  color: #e6a23c;
}

/* 调试信息样式 */
.debug-info {
  font-size: 12px;
  color: #909399;
  margin: 4px 0;
  font-style: italic;
}

/* 房屋详情样式 */
.house-detail-content {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.detail-section h4 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-item .label {
  font-size: 14px;
  color: #606266;
  min-width: 80px;
  font-weight: 500;
}

.detail-item .value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 全屏弹窗样式 */
:deep(.fullscreen-dialog) {
  .el-dialog {
    height: 96vh;
    display: flex;
    flex-direction: column;
  }
  
  .el-dialog__body {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
  }
  
  .el-dialog__header {
    padding: 20px 20px 0;
  }
  
  .el-dialog__footer {
    padding: 0 20px 20px;
  }
}

/* 功能说明样式 */
.function-description {
  background: #f5f7fa;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.function-description ol {
  margin: 0;
  padding-left: 20px;
  color: #606266;
  line-height: 1.6;
}

.function-description li {
  margin-bottom: 8px;
}

/* 表单样式 */
.owner-form {
  .form-section {
    margin-bottom: 30px;
  }
  
  .section-title {
    margin: 0 0 20px 0;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #409eff;
    padding-bottom: 8px;
  }
  
  .form-content {
    display: flex;
    gap: 30px;
  }
  
  .form-left {
    flex: 1;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .owner-form .form-content {
    flex-direction: column;
  }
  
  .owner-form .form-left {
    grid-template-columns: 1fr;
  }
}
</style>
